package mutilthread;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * Created with IntelliJ IDEA.
 * Description: 创建一个线程，计算 1 + 2 + 3 + ... + 1000 (Callable)
 * User: Li_yizYa
 * Date: 2025—04—08
 * Time: 17:27
 */
public class Demo25 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        Callable<Integer> callable = new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                int sum = 0;
                for (int i = 0; i < 1000; i++) {
                    sum += i;
                }
                return sum;
            }
        };

        FutureTask<Integer> futureTask = new FutureTask<>(callable);
        Thread t = new Thread(futureTask);
        t.start();

        // 需要通过 futureTask 拿到最终的结果
        // 此处 get 方法带有阻塞功能，如果 t 线程还没执行完，get 就会阻塞，直到 t 执行完后，get 才能返回
        // get 相当于带有返回结果的 join
        System.out.println(futureTask.get());
    }
}
